﻿using Abp.Runtime.Caching;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCore.Extensions;
using System;
using System.Collections.Generic;

namespace NetCore.Filters
{
    /// <summary>
    /// 自定义的资源Filter
    /// </summary>
    public class CustomResourceFilterAttribute : Attribute, IResourceFilter
    {
        private static readonly Dictionary<string, object> _cache = new Dictionary<string, object>();
        private string _cacheKey;
        private readonly ICacheManager _cacheManager;

        public CustomResourceFilterAttribute(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 控制器实例化之前
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            //_cacheKey= context.HttpContext.Request.Path.ToString();
            //var cacheValue = _cacheManager.GetCache(NetCoreConsts.AppName).GetOrDefault(_cacheKey);
            //if (cacheValue != null)
            //{
            //    //直接指定Result
            //    context.Result = cacheValue as ViewResult;
            //}

            ////_cacheKey = context.HttpContext.Request.Path.ToString();
            ////if (_cache.ContainsKey(_cacheKey))
            ////{
            ////    var cacheValue = _cache[_cacheKey] as ViewResult;
            ////    if (cacheValue != null)
            ////    {
            ////        //直接指定Result
            ////        context.Result = cacheValue;
            ////    }
            ////}
        }

        /// <summary>
        /// 把请求都处理完以后
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            if (_cacheKey.HasValue() && _cacheManager.GetCache(NetCoreConsts.AppName).GetOrDefault(_cacheKey) is null)
            {
                _cacheManager.GetCache(NetCoreConsts.AppName)
                    .Get(_cacheKey, () => context.Result as ViewResult);
            }

            //if (!string.IsNullOrWhiteSpace(_cacheKey) && !_cache.ContainsKey(_cacheKey))
            //{
            //    var result = context.Result as ViewResult;
            //    if (result != null)
            //    {
            //        _cache.Add(_cacheKey, result);
            //    }
            //}
        }
    }
}
